#!/bin/bash

dir=""
appname=""
appshort=""
appdir=""
mainmenu=""
menulist=()
langlist=(en zh_Hans zh_Hant)

function usage()
{
    echo "mkluciapp.sh usage:"
    echo "mkluciapp.sh create <dir> <appname> [mainmenu [menu1 [menu2 [...]]]]"
    echo "    dir : where to make app project"
    echo "    appname : LuCI application name, without prefix"
    echo "    example : mkluciapp.sh ./ upnp"
    echo "mkluciapp.sh apply <appdir> <openwrtdir>"
    echo "    appdir : luci application source code directory"
    echo "    openwrtdir : opemwrt project directory"
}

function make_app_dir()
{
    if [ -d ${appdir} ]
    then
        rm -rf ${appdir}
    fi
    mkdir -p ${appdir}
}

function set_po_content()
{
    local language=$1
    local nplurals=1
    local plural=0
    if [ ${language} == "en" ]
    then
        nplurals=0
        plural="n != 1"
    fi
    local destfile=${appdir}/po/${language}/${appshort}.po
    make_file ${destfile}
    # echo "po file:${destfile}"

    cat >> ${destfile} << EOF
sgid ""
sgstr ""
"Project-Id-Version: luci-app-${appshort}1.0.0"
"POT-Creation-Date: $(date)"
"PO-Revision-Date: $(date)"
"Last-Translator: Jason <jason.zhou@siliconwaves.com>"
"Language-Team: siliconwaves <https://siliconwaves.com/zh-CN/"
"luciapplications/${appshort}/en/>"
"Language: ${language}"
"Content-Type: text/plain; charset=UTF-8"
"Content-Transfer-Encoding: 8bit"
"Plural-Forms: nplurals=${nplurals}; plural=${plural}"
"X-Generator: Weblate 4.13.1-dev"
EOF
}

function make_po_files()
{
    mkdir -p ${appdir}/po
    for lan in ${langlist[@]}
    do
        # echo "language=$lan"
        mkdir -p ${appdir}/po/${lan}
        touch ${appdir}/po/${lan}/${appshort}.po
        set_po_content ${lan}
    done
}

function make_file()
{
    destfile=$1
    echo "make file:${destfile}"
    mkdir -p $(dirname $1;pwd)
    [ -f ${destfile} ] && rm -rf ${destfile}
    touch ${destfile}
    # echo "${destfile}"
}

function make_start_service_file()
{
    local destfile=${appdir}/root/etc/uci-defaults/luci-app-${appshort}
    make_file ${destfile}
    chmod 755 ${destfile}

    cat >> ${destfile} << EOF
    #!/bin/sh
    # 用于在ipk安装后重启服务
    /etc/init.d/rpcd reload
    exit 0
EOF
}

function make_menulist_file()
{
    local destfile=${appdir}/root/usr/share/luci/menu.d/luci-app-${appshort}.json
    make_file ${destfile}
    echo "menu file:${destfile}"

    firstchild=${menulist[0]}
    if [ x${firstchild} == "x" ]
    then
        firstchild=${appshort}
    fi

    cat >> ${destfile} << EOF
{
	"admin/${appshort}": {
		"title": "${appshort} Page",
		"order": 10,
		"action": {
			"type": "firstchild",
			"preferred": "${firstchild}",
			"recurse": true
		}
	},
EOF

    order=10
    for smenu in "${menulist[@]}"
    do
        echo "add menu: ${smenu}"
        order=$((order+10))
        cat >> ${destfile} << EOF
    "admin/${appshort}/${smenu}": {
        "title": "${smenu} Infomation",
		"order": ${order},
        "action": {
            "type": "view",
            "path": "${appshort}/${smenu}"
        },
		"depends": {
			"acl": [ "luci-app-${smenu}" ]
		}
    },
EOF
    done

    # 删除最后一个字符
    sed -i '$s/.$//' ${destfile}
    echo "}" >> ${destfile}

}

function make_acl_file()
{
    local destfile=${appdir}/root/usr/share/rpcd/acl.d/luci-app-${appshort}.json
    make_file ${destfile}
    # echo "acl file:${destfile}"

    echo "{" >> ${destfile}
    for smenu in "${menulist[@]}"
    do
        cat >> ${destfile} << EOF
    "luci-app-${smenu}": {
        "description": "luci-app-${smenu} sub module",
        "read": {
            "file": {
                "/etc/config/${appshort}": ["read"],
                "/etc/group": ["read"]
            },
            "ubus": {
                "service": [ "info" ]
            },
            "uci": ["${appshort}"]
        },
        "write": {
            "uci": ["${appshort}"]
        }
    },
EOF
    done
    # 删除最后一个字符
    sed -i '$s/.$//' ${destfile}
    echo "}" >> ${destfile}


}

function make_makefile()
{
    local destfile=${appdir}/Makefile
    make_file ${destfile}

    cat >> ${destfile} << EOF
# 加载相关规则文件，必需。
include \$(TOPDIR)/rules.mk

# 在 OpenWrt 编译菜单中显示的标题，必需
LUCI_TITLE:=application ${appshort} - LuCI interface

# 依赖关系，可选
LUCI_DEPENDS:=+luci-mod-admin-full

# 是否要限制硬件平台，可选
LUCI_PKGARCH:=all

# 版本号，可选
PKG_VERSION:=1.0.0

# 修订版本号，可选
# PKG_RELEASE:=1

# 标记日期，可选
# PKG_DATE:=20201130

# 作者信息，可选
# PKG_MAINTAINER:=OpenWrt-Life <admin@ikghx.com>

# 软件许可信息，可选
PKG_LICENSE:=Apache-2.0

# 加载相关规则文件，必需。
include ../../luci.mk

# 下面一行是 Luci 界面专用调用标识，必需，如果缺失会导致不会被加入 OpenWrt 的编译菜单中。
# 注意这一行本身就应该是屏蔽状态"
# call BuildPackage - OpenWrt buildroot signature
EOF
}

function make_single_js_file()
{
    local smenu=$1
    local destfile=${appdir}/htdocs/luci-static/resources/view/${appshort}/${smenu}.js
    make_file ${destfile}

    cat >> ${destfile} << EOF
'use strict';
'require baseclass';
'require fs';
'require rpc';
'require view';
'require dom';
'require poll';
'require uci';
'require form';

var callSystemBoard = rpc.declare({
	object: 'system',
	method: 'board'
});

var callSystemInfo = rpc.declare({
	object: 'system',
	method: 'info'
});

return view.extend({
	title: _('Primary Infomation'),

	load: function() {
		return Promise.all([
			L.resolveDefault(callSystemBoard(), {}),
			L.resolveDefault(callSystemInfo(), {}),
			fs.lines('/usr/lib/lua/luci/version.lua')
		]);
	},

	render: function(data) {
		var boardinfo   = data[0],
		    systeminfo  = data[1];

		var devinfofields = [
			_('DevManufacturer'),  'SiliconWaves',
			_('Model'),            boardinfo.model,
			_('HardwareVersion'),  'V1.0.0',
			_('SoftwareVersion'),  'V1.0.0',
			_('BootVersion'),      'V1.0.0',
			_('IPv4 address'),     '192.168.220.1',
			_('IPv6 address'),     '192.168.220.1',
			_('Device SN'),        'invalid',
			_('CMEI Code'),        'invalid',
			_('Running Time'),    '01:23:23'
		];

        var devinfotable = E('devinfotable', { 'class': 'table' });
        for (var i = 0; i < devinfofields.length; i += 2) {
            devinfotable.appendChild(E('tr', { 'class': 'tr' }, [
                E('td', { 'class': 'td left', 'width': '33%' }, [ devinfofields[i] ]),
                E('td', { 'class': 'td left' }, [ (devinfofields[i + 1] != null) ? devinfofields[i + 1] : '?' ])
            ]));
        }

		var v1 = E([], [
			E('h2', _('Device Infomation')),
			E('div', { 'class': 'cbi-map-descr' }, _('This is some device infomation')),
            E('table', { 'class': 'table' },devinfotable)

		]);


		var wifi2_4gstatusfields = [
			_('Wireless Status'),  _('Connected'),
			_('MAC address'),      '00:11:22:33:44:55',
			_('SSID name'),        'CMCC-sw-test',
			_('Security Mode'),    _('Unknown'),
			_('Channel'),          '1'
		];

        var wifi2_4gstatustable = E('wifi2_4gstatustable', { 'class': 'table' });
        for (var i = 0; i < wifi2_4gstatusfields.length; i += 2) {
            wifi2_4gstatustable.appendChild(E('tr', { 'class': 'tr' }, [
                E('td', { 'class': 'td left', 'width': '33%' }, [ wifi2_4gstatusfields[i] ]),
                E('td', { 'class': 'td left' }, [ (wifi2_4gstatusfields[i + 1] != null) ? wifi2_4gstatusfields[i + 1] : '?' ])
            ]));
        }

		var v2 = E([], [
			E('h2', _('WiFi Status(2.4G)')),
			E('div', { 'class': 'cbi-map-descr' }, _('This is some wan infomation')),
            E('table', { 'class': 'table' },wifi2_4gstatustable)
		]);

        var v = E([], [
            E('div', {}, v1),
            E('div', {}, v2),
        ]);

		return v;
	},

	handleSaveApply: null,
	handleSave: null,
	handleReset: null
});
EOF






}

function make_javascript_file()
{
    for smenu in "${menulist[@]}"
    do
        make_single_js_file ${smenu}
    done
}

function make_config_file()
{
    local destfile=${appdir}/root/etc/config/${appshort}
    make_file ${destfile}
    cat >> ${destfile} << EOF
config ${appshort}
    option appname '${appname}'
    option appver '1.0.0'
    option apptime '$(date)'
    option appfunc '${appshort} model'
EOF
}

function make_luci_app()
{
    dir=$2
    appshort=$3
    appname=luci-app-$3
    appdir=${dir}/${appname}
    if [ $# -ge 4 ]
    then
        mainmenu=$4
    else
        mainmenu=${appshort}
    fi
    # echo  "mainmenu=$mainmenu"
    # echo "args number=$#"

    menulist=()
    if [ $# -ge 5 ]
    then
        arr=("$@")
        idx=4
        while [ $idx -lt $# ]
        do
            menulist+=(${arr[$idx]})
            idx=$((idx+1))
            # echo ${menulist[@]} $idx
        done
    fi

    echo "appname=${appname}"
    for smenu in "${menulist[@]}"
    do
        echo "submenu=${smenu}"
    done

    make_app_dir
    make_makefile
    make_po_files
    make_acl_file
    make_menulist_file
    # make_start_service_file
    make_javascript_file
    make_config_file
}

function apply_luci_app()
{
    echo "apply luci-app tp opemwrt project"

    local appdir=$2
    local openwrtdir=$3
    local destdir=${openwrtdir}/feeds/luci/applications
    local solutiondir=${openwrtdir}/router_solution

    if [ ! -e ${appdir} ]
    then
        echo "app directory:${appdir} is not exit"
<<<<<<< HEAD
        exit 
=======
        exit
>>>>>>> 5404bb3c0ad90b5dcca5b42206a2f41d6bda0b7a
    fi

    if [ ! -e ${destdir} ]
    then
        echo "dest directory:${destdir} is not exit"
<<<<<<< HEAD
        exit 
=======
        exit
>>>>>>> 5404bb3c0ad90b5dcca5b42206a2f41d6bda0b7a
    fi

    if [ -e ${destdir}/${appdir} ]
    then
        rm -rf ${destdir}/${appdir}
    fi
    if [ -e ${openwrtdir}/package/feeds/luci/${appdir} ]
    then
        rm -rf ${openwrtdir}/package/feeds/luci/${appdir}
    fi

    cp -rf ${appdir} ${solutiondir}
    cp -rf ${appdir} ${destdir}
    ln -s ${destdir}/${appdir} ${openwrtdir}/package/feeds/luci/${appdir}
    echo "apply success!!!"
}

function main()
{
    if [ $# -lt 2 ]
    then
        usage
        exit
    fi

    if [ $1 == "--help" ]
    then
        usage
        exit
    fi

    if [ $1 == "create" ]
    then
        make_luci_app $@
    elif [ $1 == "apply" ]
    then
        apply_luci_app $@
    fi
}

main $@
